package xin.alum.aim.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import xin.alum.aim.constant.AimAttr;
import xin.alum.aim.model.Aim;

import java.util.List;

import static java.lang.System.*;

/**
 * @author Alum(alum @ live.cn)
 * @date 2021/8/20 18:44
 */
public class TextDecoder extends StringDecoder {

    public TextDecoder() {
        super(CharsetUtil.UTF_8);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) {
        try {
            super.decode(ctx, in, list);
            Aim.Agreement dataAgreement = ctx.channel().attr(AimAttr.AGREEMENT).get();
            if (dataAgreement != Aim.Agreement.Json) {
                ctx.channel().attr(AimAttr.AGREEMENT).set(Aim.Agreement.Text);
            }
        } catch (Exception e) {
            err.println("自定义Binary解码器");
            ctx.channel().attr(AimAttr.AGREEMENT).set(Aim.Agreement.Binary);
            list.add(in);
        }
    }
}
